package io.yyxx.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.yyxx.boot.business.entity.billDataEntity.*;
import io.yyxx.boot.business.mapper.FlightBillDataMapper;
import io.yyxx.boot.business.service.FlightBillDataService;
import io.yyxx.boot.business.service.TrainBillDataService;
import io.yyxx.boot.util.FlightBillApi;
import io.yyxx.boot.util.LastSyncTimeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class FlightBillDataServiceImpl extends ServiceImpl<FlightBillDataMapper, FlightBillData> implements FlightBillDataService {

    private static final int BATCH_SIZE = 1000;

    private final FlightBillApi flightBillApi;

    @Resource
    private LastSyncTimeUtil lastSyncTimeUtil;

    @Lazy
    @Resource
    private FlightBillDataService flightBillDataService;
    /**
     * 将获取的航班数据写入数据库,如果有新数据则进行保存
     */
    public void saveToDatabase(BillQueryParams params, String appKey, String corpToken) {
        // 1. 获取API数据,做非空判断
        if (flightBillApi == null) {
            log.error("FlightBillApi 未正确注入");
            return;
        }
        // 1. 过滤数据根据index
        FlightResponse response = flightBillApi.queryBillSettlement(params, appKey, corpToken);
        if (response == null) {
            log.info("航班账单API返回的响应对象为空");
            return;
        }

        FlightModule module = response.getModule();
        if (module == null) {
            log.info("航班账单API返回的模块对象为空");
            return;
        }

        List<FlightBillData> flightBillData = module.getDataList();
        if (flightBillData == null || flightBillData.isEmpty()) {
            log.info("航班账单API返回的航班数据列表为空或无数据");
            return;
        }

        // 2. 过滤已存在数据
        List<FlightBillData> filteredBills = filterExistingBills(flightBillData);

        // 3. 批量保存新数据
        if (!filteredBills.isEmpty()) {
            // 遍历列表，为每条数据添加当前时间
            filteredBills.forEach(bill -> {
                bill.setCreateTime(LocalDateTime.now());  // 设置当前时间
                bill.setSyncState(0);                   // 设置 syncStatus = 0
            });

            //将数据批量保存
            try {
                boolean saveResult = flightBillDataService.saveBatch(filteredBills, BATCH_SIZE);
                if (saveResult) {
                    log.info("本次成功保存 {} 条航班账单记录", filteredBills.size());
                }
            } catch (Exception e) {
                log.error("航班账单保存失败", e);
            }
        } else {
            log.info("航班没有新数据需要保存到数据库");
        }
        log.info("本次航班账单写入数据库中的数据" + filteredBills.toString());
    }

    /**
     * 过滤已存在的账单（根据每条账单的index）
     */
    private List<FlightBillData> filterExistingBills(List<FlightBillData> newBills) {
        // 2. 提取所有Index（去重）
        Set<String> indexs = newBills.stream()
                .map(FlightBillData::getIndex)
                .filter(Objects::nonNull) // 过滤掉null值
                .collect(Collectors.toSet());

        // 3. 如果提取的Index集合为空，直接返回所有账单
        if (indexs.isEmpty()) {
            return newBills;
        }

        // 4. 查询数据库中已存在的Index
        QueryWrapper<FlightBillData> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("`index`") // 只查询需要的字段
                .in("`index`", indexs);

        Set<String> existingTradeNos = baseMapper.selectList(queryWrapper)
                .stream()
                .map(FlightBillData::getIndex)
                .filter(Objects::nonNull) // 再次过滤null
                .collect(Collectors.toSet());

        // 5. 过滤新数据：保留Index不在数据库中的记录
        return newBills.stream()
                .filter(bill -> {
                    String tradeNo = bill.getIndex();
                    // 保留交易号为null的记录，或者不在数据库中的记录
                    return tradeNo == null || !existingTradeNos.contains(tradeNo);
                })
                .collect(Collectors.toList());
    }

    //从数据库中查询航班账单数据
    public List<FlightBillData> selectFlightBillData() {
        QueryWrapper<FlightBillData> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "dept_date", "dept_time",
                "arr_date", "arr_time",
                "traveler_id",
                "department_id",
                "settlement_fee",
                "book_time",
                "id",
                "sync_state",
                "project_name",
                "project_code",
                "apply_id",
                "cost_center",
                "cost_center_number",

                "fee_type_desc",//费用类型
                "settle_type_desc",//结算类型
                "bill_record_time",//入账时间

                "dept_station",  //起飞机场名称。
                "arr_station",  //到达机场名称
                "create_time", //创建时间
                "flight_no"); //  航班号

        //获取最后同步时间
        LocalDateTime lastSyncTime = lastSyncTimeUtil.getLastSyncTime("flight_last_sync_time");

        List<FlightBillData> flightBillData = baseMapper.selectList(queryWrapper);

        //在这里对trainBillData集合进行过滤，创建时间晚于lastSyncTime最后同步时间的账单才返回
        // 过滤数据：保留 create_time > lastSyncTime 的记录
        List<FlightBillData> filteredData = flightBillData.stream()
                .filter(data ->
                        data.getCreateTime() != null &&
                                data.getCreateTime().isAfter(lastSyncTime) &&
                                data.getSyncState() != 1  // 只处理未同步的数据
                )
                .peek(data -> data.setSyncState(1))
                .collect(Collectors.toList());
        if (!filteredData.isEmpty()) {
            //更改状态信息
            updateBatchById(filteredData);
        } else {
            log.info("没有需要从数据库同步的（航班）账单数据");
        }
        //过滤完折后更新最后同步时间
        lastSyncTimeUtil.updateSyncTimestamp(LocalDateTime.now(), "flight_last_sync_time");
        return filteredData;
    }
}